import { login, logout, mineInfo } from '@/api/manager'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { setAccPass, removeAccPass } from '@/utils/remember'
import { resetRouter } from '@/router'
const Base64 = require('js-base64').Base64

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password, remember } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password }).then(response => {
        const { info } = response
        commit('SET_TOKEN', info.token)
        setToken(info.token)
        // 是否记住密码 Base64加密
        if (remember) {
          setAccPass({ account: account, password: Base64.encode(password) });
        } else {
          removeAccPass();
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  mineInfo({ commit }) {
    return new Promise((resolve, reject) => {
      mineInfo().then(response => {
        const { info } = response
        try {
          info.role.authIds = info.role.auth_ids.split(',')
        } catch (error) {
          info.role.authIds = []
        }
        commit('SET_USERINFO', info)
        resolve(info)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise(resolve => {
      logout().then(() => {
        removeToken()
        resetRouter()
        commit('RESET_STATE')
        // commit('permission/RESET_STATE', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

